﻿using System.ComponentModel;
using System.Windows;
using System;
using System.Linq;
using System.Reflection;
namespace DeepEarth.Map.Core.Converters
{
    public class PositionOriginTypeConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType)
        {
            return sourceType == typeof(string) || sourceType == typeof(Point);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value.GetType() == typeof(Point))
            {
                Point point = (Point)value;

                return PointToPositionOriginConverter.Convert(point);
            }

            string positionOriginString = value.ToString();

            string[] parts = positionOriginString.Split(',').Select(s => s.Trim()).ToArray();
            if (parts.Length == 2)
            {
                return new PositionOrigin
                {
                    X = double.Parse(parts[0]),
                    Y = double.Parse(parts[1])
                };
            }

            FieldInfo field = typeof(PositionOrigin).GetField(positionOriginString, BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase);
            if (field == null)
            {
                throw new FormatException("Invalid Position Origin");
            }

            return field.GetValue(null);
        }

    }
}
